package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.OperatorConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.strategy.api.CacheService;
import com.qf.smsplatform.strategy.service.FilterChain;
import com.qf.smsplatform.strategy.util.CheckMobileOperator;
import com.qf.smsplatform.strategy.util.PushMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;


@Service(value = "mobilePhase")
@Slf4j
public class MobilePhaseStrategy implements FilterChain {

    @Resource
    private CacheService cacheService;



    @Resource
    private PushMessageUtil pushMessageUtil;


//    @Override
//    public boolean strategy(StandardSubmit submit) {
//        log.info("【号段补全策略】  号段补全策略执行啦");
//        //通过CheckMobileOperator工具类。判断手机号的运营桑
//
//        String mobile = submit.getDestMobile();
//        if (CheckMobileOperator.isChinaMobilePhoneNum(mobile)){
//
//        submit.setOperatorId(OperatorConstants.CHINA_MOBILE);
//        }else if (CheckMobileOperator.isChinaMobilePhoneNum(mobile)){
//
//            submit.setOperatorId(OperatorConstants.CHINA_UNICOM);
//        }else if (CheckMobileOperator.isChinaMobilePhoneNum(mobile)) {
//
//            submit.setOperatorId(OperatorConstants.CHINA_TELECOM);
//
//
//        }else {
//            submit.setOperatorId(OperatorConstants.CHINA_UNKNOWN);
//        }
//
//
////省市
//
//        //1.获取手机号对应的省市
//        String provinceAndCity = cacheService.get(CacheConstants.CACHE_PREFIX_PHASE + mobile.substring(0,7));
//        //2.非空判断
//        if (StringUtils.isEmpty(provinceAndCity)){
//            submit.setProvinceId(0);
//            submit.setCityId(0);
//
//        }else {
//        //3.不为空，需要使用逗号分隔
//        int index = provinceAndCity.indexOf(",");
//        String ProvinceId = provinceAndCity.substring(0, index);
//        String CityId = provinceAndCity.substring( index+1);
//
//        //4.设置到submit中
//
//        submit.setProvinceId(Integer.valueOf(ProvinceId));
//        submit.setCityId(Integer.valueOf(CityId));
//        }
//
//
////补齐管道选择
//        //根据运营商id查询出当前所有可用的channel -》key
//        Set<String> keys = cacheService.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + submit.getOperatorId() + ":*");
//            if (keys == null || keys.size() ==0){
//                log.info("【号段补全策略】  策略校验失败，当前平台没有可用的通道发送消息给当前手机 mobile = {}",submit.getDestMobile());
//                pushMessageUtil.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
//                pushMessageUtil.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
//          return  false;
//                //发送消息给mq
//
//            }
//
//        //根据查询出的key，在查询出指定的channel信息
//
//        for (String key : keys) {
//            //1.根据key查询出channel的id
//            Map channlMap = cacheService.hMGet(key);
//
//            //2.获取当前的channel的id
//            String id = (String) channlMap.get("id");
//
//
//
//            //根据当前的channelid查询出client_channel信息
//            Map clientChannel = cacheService.hMGet(CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID() + ":" + id);
//                if (clientChannel != null || clientChannel.size() != 0){
//                    //拿到了指定的客户管道信息
//
//
//
//                    //封装下发原号码
//                  submit.setSrcNumber((String) channlMap.get("spnumber") +  clientChannel.get("extendnumber"));
//                    //封装费用到submit（在submit追加一个属性）
//                    submit.setFee(Long.parseLong((String) clientChannel.get("price")));
//
//                    //补全gatewayID
//                    submit.setGatewayID(Integer.valueOf((String)(channlMap.get("id"))));
//                    log.info("【号段补全策略】 号段补全成功");
//                    return  true;
//
//                }
//
//        }
//        //判断是否找到了可用的管道信息
//
//            //没找到
//            log.info("【号段补全策略】  策略校验失败，当前客户没有绑定响应的管道信息 mobile = {}",submit.getDestMobile();
//        pushMessageUtil.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
//        pushMessageUtil.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
//
//        return false;
//}
//}
@Override
public boolean strategy(StandardSubmit submit) {
    log.info("【号段补全策略】 号段补全策略执行了....");
    String mobile = submit.getDestMobile();

    //--------------------------------------------------------------
    //-------------------------搞定运营商-------------------------------------
    //--------------------------------------------------------------
    // 通过CheckMobileOperator工具类判断当前手机号的运营商
    if(CheckMobileOperator.isChinaMobilePhoneNum(mobile)){
        // 是移动
        submit.setOperatorId(OperatorConstants.CHINA_MOBILE);
    }else if(CheckMobileOperator.isChinaUnicomPhoneNum(mobile)){
        // 是联通
        submit.setOperatorId(OperatorConstants.CHINA_UNICOM);
    }else if(CheckMobileOperator.isChinaTelecomPhoneNum(mobile)){
        // 是电信
        submit.setOperatorId(OperatorConstants.CHINA_TELECOM);
    }else{
        // 国外号码
        submit.setOperatorId(OperatorConstants.CHINA_UNKNOWN);
    }


    //--------------------------------------------------------------
    //-------------------------搞定省市-------------------------------------
    //--------------------------------------------------------------
    //1. 获取手机号对应的省市
    String provinceAndCity = cacheService.get(CacheConstants.CACHE_PREFIX_PHASE + mobile.substring(0,7));
    //2. 非空判断
    if(StringUtils.isEmpty(provinceAndCity)){
        submit.setProvinceId(0);
        submit.setCityId(0);
        // TODO  之前的return true.会导致无法执行补齐管道选择,删掉,加上else
    }else {
        //3. 不为空,使用","进行分割
        int index = provinceAndCity.indexOf(",");
        String provinceId = provinceAndCity.substring(0, index);
        String cityId = provinceAndCity.substring(index + 1);
        //4. 设置到submit中
        submit.setProvinceId(Integer.valueOf(provinceId));
        submit.setCityId(Integer.valueOf(cityId));
    }
    //------------------------------------------------------
    //---------------------补齐管道选择---------------------------------
    // 也可以将channel以运营商分类,存放在list/set结构中.
    //------------------------------------------------------

    // 根据运营商id查询出当前平台所有可用的channel ->   (CLIENT:1:1)
    Set<String> keys = cacheService.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + submit.getOperatorId() + ":*");
    if(keys == null || keys.size() == 0){
        log.info("【号段补全策略】 策略校验失败，当前平台没有可用的通道发送消息给当前手机  mobile = {}",submit.getDestMobile());
        pushMessageUtil.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
        pushMessageUtil.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
        return false;
    }

    // 根据查询出的key,查询出指定的channel信息   ->    channelid ->
    for (String key : keys) {
        //1. 根据key查询出Channel信息
        Map channelMap = cacheService.hMGet(key);
        //2. 获取当前channel的id
        String id = channelMap.get("id") + "";
        // 根据当前channelid查询出client_channel信息  ROUTER:clientID:channelID
        Map clientChannel = cacheService.hMGet(CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID() + ":" + id);
        if(clientChannel != null && clientChannel.size() != 0){
            // 拿到了指定的客户管道信息
            // 封装下发源号码.
            submit.setSrcNumber((String) channelMap.get("spnumber") + clientChannel.get("extendnumber"));
            // 封装费用到submit(在Submit对象中追加一个属性)
            submit.setFee(Long.parseLong(clientChannel.get("price") + ""));
            // 补全GatewayID
            submit.setGatewayID(Integer.valueOf(channelMap.get("id")+""));
            log.info("【号段补全策略】 号段补全成功");
            return true;
        }
    }
    // 判断是否找到了可用的管道信息,没找到
    log.info("【号段补全策略】 策略校验失败，客户没有绑定相应的管道信息..  mobile = {}",submit.getDestMobile());
    pushMessageUtil.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
    pushMessageUtil.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
    return false;
}

}